/**
 * Created by CJB on 2017/2/18.
 */

(function ($) {
	var settings = {}, roots = {};
	var _setting = {
			treeId: "",
			treeObj: null,
			data: {
				key: {
					children: "children",
					name: "name",
					title: "",
					url: "url",
					icon: "icon"
				},
				simpleData: {
					enable: false,
					idKey: "id",
					pIdKey: "pId",
					rootPId: null
				},
				keep: {
					parent: false,
					leaf: false
				}
			},
			callback: {
				onClick: null
			}
		},

		tools = {
			clone: function (obj) {
				if (obj === null) return null;
				var o = tools.isArray(obj) ? [] : {};
				for (var i in obj) {
					o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]);
				}
				return o;
			},
			eqs: function (str1, str2) {
				return str1.toLowerCase() === str2.toLowerCase();
			}
			,
			isArray: function (arr) {
				return Object.prototype.toString.apply(arr) === "[object Array]";
			}
		},
		data = {
			transformTozTreeFormat: function (setting, sNodes) {
				var i, l,
					key = setting.data.simpleData.idKey,
					parentKey = setting.data.simpleData.pIdKey,
					childKey = setting.data.key.children;
				if (!key || key == "" || !sNodes) return [];

				if (tools.isArray(sNodes)) {
					var r = [];
					var tmpMap = [];
					for (i = 0, l = sNodes.length; i < l; i++) {
						tmpMap[sNodes[i][key]] = sNodes[i];
					}
					for (i = 0, l = sNodes.length; i < l; i++) {
						if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
							if (!tmpMap[sNodes[i][parentKey]][childKey])
								tmpMap[sNodes[i][parentKey]][childKey] = [];
							tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
						} else {
							r.push(sNodes[i]);
						}
					}
					return r;
				} else {
					return [sNodes];
				}
			},
			transformat: function (setting, sNodes) {
				var i, l,
					key = setting.data.simpleData.idKey,
					parentKey = setting.data.simpleData.pIdKey,
					childKey = setting.data.key.children;
				if (!key || key == "" || !sNodes) return [];

				if (tools.isArray(sNodes)) {
					var tmpMap = {};
					for (i = 0, l = sNodes.length; i < l; i++) {
						tmpMap[sNodes[i][key]] = sNodes[i];
					}
					return tmpMap;
				} else {
					return sNodes;
				}
			},
			transformToArrayFormat: function (setting, nodes) {
				if (!nodes) return [];
				var childKey = setting.data.key.children,
					r = [];
				if (tools.isArray(nodes)) {
					for (var i=0, l=nodes.length; i<l; i++) {
						r.push(nodes[i]);
						if (nodes[i][childKey])
							r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));
					}
				} else {
					r.push(nodes);
					if (nodes[childKey])
						r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));
				}
				return r;
			}
		},
		view = {
			appendNodes: function (setting, level, nodes) {
				if (!nodes) return [];
				var html = [],
					childKey = setting.data.key.children,
					name = setting.data.key.name,
					url = setting.data.key.url,
					idKey = setting.data.simpleData.idKey,
					title = setting.data.key.title;
				for (var i = 0, l = nodes.length; i < l; i++) {
					var node = nodes[i];
					var tmp = [];
					tmp.push('<li');
					if (childKey && node[childKey] && node[childKey].length)
						tmp.push(' class="link"');
					tmp.push('>');
					if(node.className){
						tmp.push('<i class="icon');
						tmp.push(' ' + node.className);
						tmp.push('"></i>');
					}
					//显示菜单名字
					tmp.push('<a');
					tmp.push(' id="');
					tmp.push(setting.treeId);
					tmp.push('_');
					tmp.push(node[idKey]);
					tmp.push('_a"');
					if (url && node[url]) {
						tmp.push(' href="');
						tmp.push(node[url]);
						tmp.push('"');
					} else {
						tmp.push(' href="#" target="_self"');
					}
					if (title && node[title]) {
						tmp.push(' title="');
						tmp.push(node[title]);
						tmp.push('"');
					}
					tmp.push('>');
					if (name && setting.data.key.name) {
						tmp.push(node[name]);
					}
					tmp.push('</a>');
					if (childKey && node[childKey] && node[childKey].length)
						tmp.push('<i class="fa fa-chevron-down"></i>');
					else
						tmp.push('<i class="fa fa-angle-right"></i>');

					//下级菜单
					if (childKey && node[childKey] && node[childKey].length) {
						//tmp.push('<i class="fa fa-chevron-down"></i></div>');

						//添加子菜单
						tmp.push('<ul class="submenu">');
						tmp = tmp.concat(this.appendNodes(setting, level + 1, node[childKey]));
						tmp.push('</ul>');
					}

					tmp.push('</li>');
					html = html.concat(tmp);
				}
				return html;
			},
			createNodes: function (setting, level, nodes, parentNode) {
				if (!nodes || nodes.length == 0) return;
				var childKey = setting.data.key.children;
				var zTreeHtml = view.appendNodes(setting, level, nodes);
				if (!parentNode) {
					setting.treeObj.append(zTreeHtml.join(''));
				} else {

				}
			},
			addListener: function (setting) {
				/*setting.treeObj.find('li').hover(function () {
					$(this).children('ul').stop(true, false).show('normal');
				}, function () {
					$(this).children('ul').stop(true, false).hide('normal');
				});*/
				setting.treeObj.find('.submenu').click(function (event) {
					event.stopPropagation();
				});
				// 点击菜单，打开子菜单
				var links = setting.treeObj.find('.link');
				links.on('click', {tree:setting.treeObj}, view.dropdown)
			},
			dropdown : function(e) {
				var $this = $(this),
				$next = $this.find('.submenu');

				$next.slideToggle();
				$this.toggleClass('open');

				e.data.tree.find('.submenu').not($next).slideUp().parent().removeClass('open');
			},
			bindEvent: function (setting, nodes) {
				var treeO = setting.treeObj;
				treeO.find("li>a").click(function (event) {
					var href = $(this).attr('href');
					if(href == '#' && $(this).parent().find('.submenu').length)
						return ;
					treeO.find('li').removeClass('selected');
					$(this).parent('li').addClass('selected');
					//$(this).parents('li').addClass('selected');
					if (setting.callback.onClick) {
						var aId = $(this).attr("id");
						var ids = aId.split("_");
						var keyId = ids[1];
						setting.callback.onClick(nodes[keyId], event);
					}
				});
			}
		};


	$.fn.zreeMenu = {
		init: function (obj, zSetting, zNodes) {
			var setting = tools.clone(_setting);
			$.extend(true, setting, zSetting);
			setting.treeId = obj.attr("id");
			setting.treeObj = obj;
			setting.treeObj.empty();
			settings[setting.treeId] = setting;
			zNodes = zNodes ? tools.clone(tools.isArray(zNodes) ? zNodes : [zNodes]) : [];
			var dataNodes = [];
			if (setting.data.simpleData.enable) {
				dataNodes = data.transformat(setting, tools.clone(zNodes));
				zNodes = data.transformTozTreeFormat(setting, zNodes);
			} else {
				dataNodes = data.transformToArrayFormat(setting, tools.clone(zNodes));
				dataNodes = data.transformat(setting, tools.clone(dataNodes));
			}
			view.createNodes(setting, 0, zNodes);
			view.addListener(setting);
			view.bindEvent(setting, dataNodes);
		}

	};
})
(jQuery);